//影像检索
var maps = [];
var compareDrawGraphicsLayer; //用于主地图上添加绘制图形的图层
var drawGraphic; //用于主地图上添加绘制的图形

var compareDrawGraphicsLayers = []; //用于对比用的六个地图上添加绘制图形的图层
var drawGraphics = []; //用于对比用的六个地图上添加绘制的图形

var initImageCompare;

var tiledMapServiceLayers = {};
var addToMap;

var activeMap;
var clearActiveMapEvents;
var bindActiveMapEvents;

require([
    "dojo/ready",
    "dojo/parser",
    "dojo/_base/array",
    "dojo/parser", "dojo/on", "dojo/dom",

    "esri/symbols/SimpleMarkerSymbol",
    "esri/symbols/SimpleLineSymbol",
    "esri/symbols/SimpleFillSymbol",
    "esri/symbols/PictureMarkerSymbol",

    "esri/toolbars/draw",
    "esri/graphic",
    "esri/map",
    "esri/geometry/Extent",
    "esri/Color",

    "esri/layers/GraphicsLayer",
    "esri/layers/ArcGISDynamicMapServiceLayer",
    "esri/layers/ArcGISTiledMapServiceLayer",

    "dojo/domReady!"
], function (ready, parser, arrayUtils,
    parser, on, dom, SimpleMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, PictureMarkerSymbol,
    Draw, Graphic, Map, Extent, Color, GraphicsLayer, ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer) {

    parser.parse();

    initImageCompare = function () {
        createCompareDrawToolbar();
        
        compareDrawGraphicsLayer = new GraphicsLayer({
            id: "compareDrawGraphicsLayer",
        });

        var initExtent = new esri.geometry.Extent();
        initExtent.xmin = -96772;
        initExtent.xmax = 80772;
        initExtent.ymin = -28592;
        initExtent.ymax = 30000;
        initExtent.setSpatialReference(shanghaiSpatialRef);

        //初始化对比用地图
        for (let i = 0; i < 6; i++) {
            var cmap = new Map("map_" + i, {
                extent: initExtent,
                maxZoom: 8,
                minZoom: 0,
                logo: false
            });

            maps.push(cmap);
        }

        T_LAYERS.forEach((item) => {
            if(item.type==="air") {
                const layerId = item.layerId;
                const url = item.url;
                const visible = item.visible;
    
                var tiledMapServiceLayer = new ArcGISTiledMapServiceLayer(url, {
                    id: layerId,
                    visible: visible
                });
    
                tiledMapServiceLayers[layerId] = tiledMapServiceLayer;
    
                let radio = `<label class="radio_label">
                    <input class="new_radio" type="checkbox" name="imageYear" value="${layerId}">
                    <span class="new_checkbox radioInput"></span>${layerId}年影像
                </label>`
                $("#imageCompareRadios").append(radio);
            }       
        })

        //地图联动事件，每次切换活动地图时，重新绑定联动事件，防止非活动地图的范围变化触发联动事件
        var activeMapEventHandlers = [];

        maps.forEach(function (map) {
            map.on("mouse-over", function (evt) { //鼠标在哪个地图上，该地图就是激活地图
                activeMap = map;
                clearActiveMapEvents();
                bindActiveMapEvents();
            });
        });


        clearActiveMapEvents = function () {
            activeMapEventHandlers.forEach(function (eventHandler) {
                eventHandler.remove();
            });
            activeMapEventHandlers = [];
        }

        bindActiveMapEvents = function () {
            //放大联动
            activeMapEventHandlers.push(activeMap.on("zoom-end", function (evt) {
                maps.forEach(function (map) {
                    if (map != activeMap) {
                        map.setExtent(evt.extent);
                    }
                });
            }));
            //平移联动
            activeMapEventHandlers.push(activeMap.on("pan-end", function (evt) {
                maps.forEach(function (map) {
                    if (map != activeMap) {
                        map.setExtent(evt.extent);
                    }
                });
            }));
        }

        initChangeDetection();

    }

    //绘图功能
    function createCompareDrawToolbar(themap) {
        toolbar = new Draw(map, {
            showTooltips: true
        });

        toolbar.on("draw-complete", addToMap);
    }

    addToMap = function (evt) {
        var symbol;
        drawGraphic = null;
        drawGraphics = [];
        compareDrawGraphicsLayers = [];

        toolbar.deactivate();
        switch (evt.geometry.type) {
            case "point":
            case "multipoint":
                symbol = new SimpleMarkerSymbol({
                    "color": [238, 69, 0, 64],
                    "size": 6,
                    "angle": 0,
                    "xoffset": 0,
                    "yoffset": 0,
                    "type": "esriSMS",
                    "style": "esriSMSCircle",
                    "outline": {
                        "color": [238, 69, 0, 160],
                        "width": 1,
                        "type": "esriSLS",
                        "style": "esriSLSSolid"
                    }
                });
                break;
            case "polyline":
                symbol = new SimpleLineSymbol({
                    "color": [255, 60, 0],
                    "width": 1,
                    "type": "esriSLS",
                    "style": "esriSLSSolid"
                });
                break;
            default:
                symbol = highlightPolySymbol;
                break;
        }
        drawGraphic = new Graphic(evt.geometry, symbol);

        for (i = 0; i < 6; i++) {
            var graphic = new Graphic(evt.geometry, symbol);
            var layer = new GraphicsLayer();
            layer.add(graphic);
            drawGraphics.push(graphic);
            compareDrawGraphicsLayers.push(layer);
        }

        compareDrawGraphicsLayer.add(drawGraphic);
        map.addLayer(compareDrawGraphicsLayer);

    }

    //为每个绘图按钮绑定click事件

    var drawCollection = ["polygon", "freehand_polygon", "circle"];

    drawCollection.map((item) => {
        const buttonId = "draw_" + item;

        on(dom.byId(buttonId), "click", function activateTool() {
            var tool = buttonId.toUpperCase().substring(5);
            compareDrawGraphicsLayer.clear();

            toolbar.activate(Draw[tool]);
        });

    })

    on(dom.byId("clear_draw"), "click", function () {
        compareDrawGraphicsLayer.clear();
        map.infoWindow.hide();
    });


    //触发对比功能
    on(dom.byId("imageCompareBtn"), "click", function () {
        var length = $("input[name='imageYear']:checked").length;
        if (length > 3) {
            $("#compareMapRow2").css("display", "flex");
            $(".compareMapRow").css("height", "50%");
        } else {
            $("#compareMapRow2").hide();
            $(".compareMapRow").css("height", "100%");
        }

        if (length < 2) {
            warningAlert("至少选择两个年份的影像！");

            // alert("至少选择两个年份的影像！");
            return;
        }

        if (length > 6) {
            warningAlert("最多选择六个年份的影像！");

            // alert("最多选择六个年份的影像！");
            return;
        }

        $("#mainMap").hide();
        $("#compareMap").show();

        // var years = [];;
        $("input[name='imageYear']:checked").each(function (i) {

            var year = $(this).val()

            if (length == 4 && (i == 2 || i == 3)) {
                // maps[i + 1].removeAllLayers();
                tLayer = tiledMapServiceLayers[year];
                maps[i + 1].addLayer(tiledMapServiceLayers[year]);
                maps[i + 1].addLayer(compareDrawGraphicsLayers[i + 1]);
                $("#map_" + (i + 1)).show();
                $("#label_" + (i + 1)).text(year + "年影像");

                if (typeof (drawGraphics[i + 1]) != "undefined") {
                    var extent = drawGraphics[i + 1].geometry.getExtent();
                    maps[i + 1].setExtent(extent, true);
                }

            } else {
                // maps[i].removeAllLayers();
                tLayer = tiledMapServiceLayers[year];

                maps[i].addLayer(tiledMapServiceLayers[year]);

                maps[i].addLayer(compareDrawGraphicsLayers[i]);
                $("#map_" + i).show();
                $("#label_" + i).text(year + "年影像");

                if (typeof (drawGraphics[i]) != "undefined") {
                    var extent = drawGraphics[i].geometry.getExtent();
                    maps[i].setExtent(extent, true);
                }
            }

        });
    })
});

$("#backMain").click(function () {
    $("#mainMap").show();
    $("#compareMap").hide();

    compareMapsHide();
});

function compareMapsHide() {
    for (var i = 0; i < 6; i++) {
        $("#map_" + i).hide();
        maps[i].removeAllLayers();

        maps[i].setExtent(initExtent);
    }
}



$("#imageCompareResetBtn").click(function () {
    imageCompareReset();

});

function imageCompareReset() {
    var length = $("input[name='imageYear']:checked").length;
    for (var i = 0; i < length; i++) {
        $("input[name='imageYear']:checked")[0].click();

    }

    drawGraphic = null;
    compareDrawGraphicsLayer.clear();
}

function compareMapsReset() {
    //初始化
    //maps清空图层、div隐藏、drawGraphics、compareDrawGraphicsLayers清空
    drawGraphics = [];
    compareDrawGraphicsLayers = [];

    for (var i = 0; i < 6; i++) {
        maps[i].removeAllLayers();
        $("#map_" + i).hide();
        maps[i].setExtent(initExtent);
    }
}